package cn.jinjimi.app.util;

import android.app.Activity;
import android.view.View;
import android.view.ViewTreeObserver;

import cn.jinjimi.base.util.AndroidUtils;

/**
 * Created by lforxeverc on 2017/7/7.
 */

public abstract class KeyboardHelper {
    private Activity mAty;
    private ViewTreeObserver.OnGlobalLayoutListener mRootViewListener;
    private boolean isOpened;
    private int mKeyBoardHigh;

    public KeyboardHelper(Activity mAty) {
        this.mAty = mAty;
    }

    public void onCreate() {
        if (mAty == null || mRootViewListener != null)
            return;
        final View activityRootView = mAty.getWindow().getDecorView().findViewById(android.R.id.content);
        mRootViewListener = new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {

                int heightDiff = activityRootView.getRootView().getHeight() - activityRootView.getHeight() - AndroidUtils.getVirtualViewHigh(mAty);
                if (heightDiff > 100) {
                    mKeyBoardHigh = heightDiff;
                    if (!isOpened) {
                        isOpened = true;
                        onOpenKeyboard();
                    }
                } else {
                    if (isOpened) {
                        isOpened = false;
                        onCloseKeyboard();
                    }
                }
            }
        };
        activityRootView.getViewTreeObserver().addOnGlobalLayoutListener(mRootViewListener);
    }

    protected abstract void onOpenKeyboard();

    protected abstract void onCloseKeyboard();

    public void onDestroy() {
        if (mAty != null) {
            View activityRootView = mAty.getWindow().getDecorView().findViewById(android.R.id.content);
            activityRootView.getViewTreeObserver().removeOnGlobalLayoutListener(mRootViewListener);
            mAty = null;
        }
    }

    public int getKeyBoardHigh() {
        return mKeyBoardHigh;
    }

    public boolean isOpen() {
        return isOpened;
    }
}
